/**
 * 本地存储工具函数
 */

/**
 * 设置本地存储
 * @param key 键
 * @param value 值
 */
export function setStorage(key: string, value: any): void {
  try {
    const data = JSON.stringify(value)
    uni.setStorageSync(key, data)
  } catch (error) {
    console.error('设置本地存储失败:', error)
  }
}

/**
 * 获取本地存储
 * @param key 键
 * @param defaultValue 默认值
 */
export function getStorage<T>(key: string, defaultValue?: T): T | null {
  try {
    const data = uni.getStorageSync(key)
    if (data) {
      return JSON.parse(data)
    }
    return defaultValue || null
  } catch (error) {
    console.error('获取本地存储失败:', error)
    return defaultValue || null
  }
}

/**
 * 删除本地存储
 * @param key 键
 */
export function removeStorage(key: string): void {
  try {
    uni.removeStorageSync(key)
  } catch (error) {
    console.error('删除本地存储失败:', error)
  }
}

/**
 * 清空本地存储
 */
export function clearStorage(): void {
  try {
    uni.clearStorageSync()
  } catch (error) {
    console.error('清空本地存储失败:', error)
  }
}

/**
 * 检查本地存储是否存在
 * @param key 键
 */
export function hasStorage(key: string): boolean {
  try {
    const data = uni.getStorageSync(key)
    return data !== ''
  } catch (error) {
    return false
  }
}

/**
 * 获取所有存储的键
 */
export function getStorageKeys(): string[] {
  try {
    const info = uni.getStorageInfoSync()
    return info.keys
  } catch (error) {
    console.error('获取存储键失败:', error)
    return []
  }
}

/**
 * 获取存储信息
 */
export function getStorageInfo(): {
  keys: string[]
  currentSize: number
  limitSize: number
} {
  try {
    return uni.getStorageInfoSync()
  } catch (error) {
    console.error('获取存储信息失败:', error)
    return {
      keys: [],
      currentSize: 0,
      limitSize: 0
    }
  }
}

/**
 * 异步设置本地存储
 * @param key 键
 * @param value 值
 */
export function setStorageAsync(key: string, value: any): Promise<void> {
  return new Promise((resolve, reject) => {
    try {
      const data = JSON.stringify(value)
      uni.setStorage({
        key,
        data,
        success: () => resolve(),
        fail: (error) => reject(error)
      })
    } catch (error) {
      reject(error)
    }
  })
}

/**
 * 异步获取本地存储
 * @param key 键
 * @param defaultValue 默认值
 */
export function getStorageAsync<T>(key: string, defaultValue?: T): Promise<T | null> {
  return new Promise((resolve) => {
    uni.getStorage({
      key,
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          resolve(data)
        } catch (error) {
          resolve(defaultValue || null)
        }
      },
      fail: () => {
        resolve(defaultValue || null)
      }
    })
  })
}

/**
 * 异步删除本地存储
 * @param key 键
 */
export function removeStorageAsync(key: string): Promise<void> {
  return new Promise((resolve, reject) => {
    uni.removeStorage({
      key,
      success: () => resolve(),
      fail: (error) => reject(error)
    })
  })
}

/**
 * 异步清空本地存储
 */
export function clearStorageAsync(): Promise<void> {
  return new Promise((resolve, reject) => {
    uni.clearStorage({
      success: () => resolve(),
      fail: (error) => reject(error)
    })
  })
}

/**
 * 存储管理器
 */
export class StorageManager {
  private prefix: string

  constructor(prefix = 'app_') {
    this.prefix = prefix
  }

  /**
   * 设置存储
   * @param key 键
   * @param value 值
   */
  set(key: string, value: any): void {
    setStorage(this.prefix + key, value)
  }

  /**
   * 获取存储
   * @param key 键
   * @param defaultValue 默认值
   */
  get<T>(key: string, defaultValue?: T): T | null {
    return getStorage<T>(this.prefix + key, defaultValue)
  }

  /**
   * 删除存储
   * @param key 键
   */
  remove(key: string): void {
    removeStorage(this.prefix + key)
  }

  /**
   * 检查是否存在
   * @param key 键
   */
  has(key: string): boolean {
    return hasStorage(this.prefix + key)
  }

  /**
   * 清空所有带前缀的存储
   */
  clear(): void {
    const keys = getStorageKeys()
    keys.forEach(key => {
      if (key.startsWith(this.prefix)) {
        removeStorage(key)
      }
    })
  }
}

// 创建默认存储管理器实例
export const storage = new StorageManager()
